package com.lzx.iteam.net;

import android.content.Context;
import android.os.Message;
import android.util.Log;
import com.lzx.iteam.bean.AttendanceClassData;
import com.lzx.iteam.bean.AttendanceData;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.StringUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import static com.lzx.iteam.DialerApp.mContext;

/**
 * Created by Megan on 16/4/11.
 */
public class GetMySubList extends CcMsgStructure {

    private static final String TAG = "GetAttendanceList";

    private Message mmCallback;

    public GetMySubList(Message callback) {
        mmCallback = callback;
    }

    @Override
    public void onReceive(JSONObject data) {
        ArrayList<AttendanceClassData> classDatas = new ArrayList<AttendanceClassData>();
        try {
            JSONObject jsonObject = data.getJSONObject(AsynHttpClient.KEY_CC_DATA);
            JSONArray jsonArray = jsonObject.getJSONArray(AsynHttpClient.KEY_SUB_ATTENDANCES);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject obj = jsonArray.getJSONObject(i);
                AttendanceClassData classData = new AttendanceClassData();
                classData.setSub_name(obj.getString("sub_name"));
                classData.setDate(obj.getLong("date"));
                classData.setStart_work_time(obj.getString("start_work_time"));
                classData.setEnd_work_time(obj.getString("end_work_time"));
                if (obj.has("noon_end_time")){
                    classData.setIs_quartic(1);
                    classData.setNoon_end_time(obj.getString("noon_end_time"));
                    classData.setNoon_start_time(obj.getString("noon_start_time"));
                }
                classDatas.add(classData);
            }
        } catch (JSONException e) {
            Log.e("My_JSONException",e.toString());
        }
        if (mmCallback != null)
        {
            mmCallback.obj = classDatas;
            mmCallback.arg1 = 0;
            mmCallback.sendToTarget();
            return;
        }

    }

    @Override
    public void onError(int error, Object ret) {
        Log.d(TAG, "onError : " + error + " ret: " + ret);
        String errorMsg = null;
        if (ret != null) {
            JSONObject jData = null;
            try {
                jData = new JSONObject(ret.toString());
                errorMsg = jData.getString("msg");
            } catch (JSONException e) {
                errorMsg = "服务端数据解析失败!";
                e.printStackTrace();
            }

        }
        if (mmCallback != null) {
            mmCallback.arg1 = error;
            if (!StringUtil.isEmpty(errorMsg)) {
                mmCallback.obj = errorMsg;
            } else {
                mmCallback.obj = Constants.NETWORK_WRROR;
            }
            mmCallback.sendToTarget();
        }

    }
}